 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=55 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Implementing toString
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='&#043;,append,debug,toString,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Implementing toString</div>

<div class='main-body'>
 
<br>The <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#toString()">toString</a></tt>
method is widely implemented. It provides a simple, convenient mechanism
for debugging classes during development.
It is also widely used for logging, and for passing informative error messages
to <tt>Exception</tt> constructors and assertions. When used in these
<em>informal</em> ways, the exact format of <tt>toString</tt> is not part of the 
<a href='TopicAction63b6-2.html'>contract</a> of the method, and callers should not rely on the exact format 
of the returned <tt>String</tt>.

<p>The <tt>toString</tt> method may <em>occasionally</em> be used more formally,
however. An example is a simple mechanism for translating an object into a 
well-defined textual form (<tt>toString</tt>) and back again (<tt>valueOf</tt>).
In this case, it is particularly important to specify the exact form of such text in javadoc. 

<p>When implementing <tt>toString</tt>, <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html">StringBuilder</a></tt>
can be used instead of the + concatenation operator, since the <tt>StringBuilder.append</tt>
operation is slightly faster.

<p><b>Example 1</b>
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Truck {

  <span class='comment'>/** Simple test harness.  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs){
    Truck planetKiller = <span class='keyword'>new</span> Truck();
    System.out.println(planetKiller);
  }

  <span class='comment'>/**
  * Intended only for debugging.
  *
  * &lt;P&gt;Here, the contents of every field are placed into the result, with
  * one field per line.
  */</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> String toString() {
    StringBuilder result = <span class='keyword'>new</span> StringBuilder();
    String NEW_LINE = System.getProperty(<span class='literal'>"line.separator"</span>);

    result.append(<span class='keyword'>this</span>.getClass().getName() + <span class='literal'>" Object {"</span> + NEW_LINE);
    result.append(<span class='literal'>" Name: "</span> + fName + NEW_LINE);
    result.append(<span class='literal'>" Number of doors: "</span> + fNumDoors + NEW_LINE);
    result.append(<span class='literal'>" Year manufactured: "</span> + fYearManufactured + NEW_LINE );
    result.append(<span class='literal'>" Color: "</span> + fColor + NEW_LINE);
    <span class='comment'>//Note that Collections and Maps also override toString
</span>    result.append(<span class='literal'>" Options: "</span> + fOptions + NEW_LINE);
    result.append(<span class='literal'>"}"</span>);

    <span class='keyword'>return</span> result.toString();
  }

  <span class='comment'>//..other methods elided
</span>  
  <span class='comment'>// PRIVATE //
</span>
  <span class='keyword'>private</span> String fName = <span class='literal'>"Dodge"</span>;
  <span class='keyword'>private</span> <span class='keyword'>int</span> fNumDoors = <span class='literal'>2</span>;
  <span class='keyword'>private</span> Date fYearManufactured = <span class='keyword'>new</span> Date();
  <span class='keyword'>private</span> String fColor = <span class='literal'>"Fuchsia"</span>;
  <span class='keyword'>private</span> List&lt;String&gt; fOptions = Arrays.asList(<span class='literal'>"Air Conditioning"</span>);
}  
</PRE>
<br>
<br>Example output :
<PRE>
Truck Object {
 Name: Dodge
 Number of doors: 2
 Year manufactured: Wed Aug 29 15:49:10 ADT 2007
 Color: Fuchsia
 Options: [Air Conditioning]
}
</PRE>

<P><b>Example 2</b>
<p>This implementation uses reflection to inspect
both field names and field values. Note that superclass fields do not
contribute to this implementation.
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.lang.reflect.Field;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Van {

  <span class='comment'>/**
  * Build a Van object and display its textual representation.
  *
  * Note that the Collection classes have
  * their own implementation of &lt;code&gt;toString&lt;/code&gt;, as exemplified here
  * by the List field holding the Options.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... arguments) {
    List&lt;String&gt; options = <span class='keyword'>new</span> ArrayList&lt;String&gt;();
    options.add(<span class='literal'>"Air Conditioning"</span>);
    options.add(<span class='literal'>"Leather Interior"</span>);

    Van van = <span class='keyword'>new</span> Van( <span class='literal'>"Dodge"</span>, <span class='literal'>4</span>, <span class='keyword'>new</span> Date(), <span class='literal'>"Blue"</span>, options);
    System.out.println(van);
  }

  <span class='keyword'>public</span> Van(
    String aName,
    <span class='keyword'>int</span> aNumDoors,
    Date aYearManufactured,
    String aColor,
    List&lt;String&gt; aOptions
  ){
    fName = aName;
    fNumDoors = aNumDoors;
    fYearManufactured = aYearManufactured;
    fColor = aColor;
    fOptions = aOptions;
  }

  <span class='comment'>//..other methods elided
</span>
  <span class='comment'>/**
  * Intended only for debugging.
  *
  * &lt;P&gt;Here, a generic implementation uses reflection to print
  * names and values of all fields &lt;em&gt;declared in this class&lt;/em&gt;. Note that
  * superclass fields are left out of this implementation.
  *
  * &lt;p&gt;The format of the presentation could be standardized by using
  * a MessageFormat object with a standard pattern.
  */</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> String toString() {
    StringBuilder result = <span class='keyword'>new</span> StringBuilder();
    String newLine = System.getProperty(<span class='literal'>"line.separator"</span>);

    result.append( <span class='keyword'>this</span>.getClass().getName() );
    result.append( <span class='literal'>" Object {"</span> );
    result.append(newLine);

    <span class='comment'>//determine fields declared in this class only (no fields of superclass)
</span>    Field[] fields = <span class='keyword'>this</span>.getClass().getDeclaredFields();

    <span class='comment'>//print field names paired with their values
</span>    <span class='keyword'>for</span> ( Field field : fields  ) {
      result.append(<span class='literal'>"  "</span>);
      <span class='keyword'>try</span> {
        result.append( field.getName() );
        result.append(<span class='literal'>": "</span>);
        <span class='comment'>//requires access to private field:
</span>        result.append( field.get(<span class='keyword'>this</span>) );
      }
      <span class='keyword'>catch</span> ( IllegalAccessException ex ) {
        System.out.println(ex);
      }
      result.append(newLine);
    }
    result.append(<span class='literal'>"}"</span>);

    <span class='keyword'>return</span> result.toString();
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> String fName;
  <span class='keyword'>private</span> <span class='keyword'>int</span> fNumDoors;
  <span class='keyword'>private</span> Date fYearManufactured;
  <span class='keyword'>private</span> String fColor;
  <span class='keyword'>private</span> List&lt;String&gt; fOptions;
} 
</PRE>
<br>
<br>Example output :
<p><tt>Van Object {</tt>
<br><tt>&nbsp; fName: Dodge</tt>
<br><tt>&nbsp; fNumDoors: 4</tt>
<br><tt>&nbsp; fYearManufactured: Thu Sep 30 19:16:14 EDT 2004</tt>
<br><tt>&nbsp; fColor: Blue</tt>
<br><tt>&nbsp; fOptions: [Air Conditioning, Leather Interior]</tt>
<br><tt>}</tt>

<P><b>Example 3</b>
<P>The <a href='TopicAction5f31-2.html'>WEB4J</a> tool 
provides a utility method for implementing <tt>toString</tt> in a single 
line of code. Its implementation uses reflection.
<br>
<PRE>

<span class='keyword'>import</span> java.math.BigDecimal;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelCtorException;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelUtil;
<span class='keyword'>import</span> hirondelle.web4j.model.Id;
<span class='keyword'>import</span> hirondelle.web4j.model.Check;
<span class='keyword'>import</span> hirondelle.web4j.util.Util;
<span class='keyword'>import</span> hirondelle.web4j.model.Validator;

<span class='comment'>/**  Model Object for a Restaurant. */</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Resto {

  <span class='comment'>/**
  * Full constructor.
  *  
  * @param aId underlying database internal identifier (optional) 1..50 characters
  * @param aName of the restaurant (required), 2..50 characters
  * @param aLocation street address of the restaurant (optional), 2..50 characters
  * @param aPrice of the fish and chips meal (optional) $0.00..$100.00
  * @param aComment on the restaurant in general (optional) 2..50 characters
  */</span>
  <span class='keyword'>public</span> Resto(
    Id aId, String aName, String aLocation, BigDecimal aPrice, String aComment
  ) <span class='keyword'>throws</span> ModelCtorException {
    fId = aId;
    fName = Util.trimPossiblyNull(aName);
    fLocation = Util.trimPossiblyNull(aLocation);
    fPrice = aPrice;
    fComment = Util.trimPossiblyNull(aComment);
    validateState();
  }
  
  <span class='keyword'>public</span> Id getId() { <span class='keyword'>return</span> fId; }
  <span class='keyword'>public</span> String getName() {  <span class='keyword'>return</span> fName; }
  <span class='keyword'>public</span> String getLocation() {  <span class='keyword'>return</span> fLocation;  }
  <span class='keyword'>public</span> BigDecimal getPrice() { <span class='keyword'>return</span> fPrice; }
  <span class='keyword'>public</span> String getComment() {  <span class='keyword'>return</span> fComment; }

  <span class='comment'>/** Intended for debugging only.  */</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> String toString() {
    <span class='keyword'>return</span> ModelUtil.toStringFor(<span class='keyword'>this</span>);
  }

  <span class='comment'>//..elided
</span>
  <span class='comment'>//PRIVATE//
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> Id fId;
  <span class='keyword'>private</span> <span class='keyword'>final</span> String fName;
  <span class='keyword'>private</span> <span class='keyword'>final</span> String fLocation;
  <span class='keyword'>private</span> <span class='keyword'>final</span> BigDecimal fPrice;
  <span class='keyword'>private</span> <span class='keyword'>final</span> String fComment;
 
  <span class='comment'>//..elided
</span>
}
 
</PRE>
<br>
<br>Example output :
<PRE>
hirondelle.fish.main.resto.Resto {
Name: Cedars Eatery
Location: Water and Prince
Id: 6
Comment: Big portions
Price: 7.89
}
</PRE>

<br><b>Example 4</b>
<p><tt>QuoteField</tt> is a <a href='TopicAction2161-2.html'>type safe enumeration</a>.
The return value of <tt>toString</tt> is used in the normal operation of the program - not just 
for logging.
Note that it forms a pair with the <tt>valueFrom(String)</tt> method, since one formats
the object into a <tt>String</tt>, and the other parses a <tt>String</tt>
into an object. 
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.stocks.table;

<span class='comment'>/**
* Enumeration for the fields of the 
* {@link hirondelle.stocks.quotes.Quote} class.
* 
* Advantages to using this class as part of a table model :
* &lt;ul&gt;
* &lt;li&gt; can parse text which maps table columns to fields
* &lt;li&gt; can be used for column names
* &lt;li&gt; length of &lt;tt&gt;QuoteField.values()&lt;/tt&gt; gives the column count
* &lt;/ul&gt;
*/</span>
<span class='keyword'>public</span> <span class='keyword'>enum</span> QuoteField  { 

  Stock(<span class='literal'>"Stock"</span>),
  Price(<span class='literal'>"Price"</span>),
  Change(<span class='literal'>"Change"</span>),
  PercentChange(<span class='literal'>"%Change"</span>),
  Profit(<span class='literal'>"Profit"</span>),
  PercentProfit(<span class='literal'>"%Profit"</span>);

  <span class='comment'>/**
  * Return a text representation of the &lt;tt&gt;QuoteField&lt;/tt&gt;.
  *
  * Return values : &lt;tt&gt;Stock, Price, Change, %Change, Profit, %Profit&lt;/tt&gt;.
  * @return value contains only letters, and possibly a percent sign.
  */</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> String toString() { 
    <span class='keyword'>return</span> fName;  
  }

  <span class='comment'>/** 
  * Parse text into a &lt;tt&gt;QuoteField&lt;/tt&gt;.
  * 
  * &lt;P&gt;The text is matched according to the value of {@link #toString()}, 
  * not from the symbolic name of the enumerated item.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> QuoteField valueFrom(String aText){
    <span class='keyword'>for</span> (QuoteField quoteField: values()){
      <span class='keyword'>if</span>( quoteField.toString().equals(aText)) {
        <span class='keyword'>return</span> quoteField;
      }
    }
    <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Cannot parse into a QuoteField: "</span> + aText);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>final</span> String fName;

  <span class='comment'>/**
  * @param aName only letters and percent sign are valid characters.
  */</span>
  <span class='keyword'>private</span> QuoteField (String aName) { 
    fName = aName;
  }
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction851d-2.html?Id=4'>String concatenation does not scale</a> <br>
 
  
  <a href='TopicAction8d16-2.html?Id=21'>Factory methods</a> <br>
 
  
  <a href='TopicActiond1f0-2.html?Id=131'>Arrays as String </a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='55'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=55 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
